<?php

  /*
     Simple way how to insert missing data into TMEP database from TH2E LOG

     Copy this script to root folder of TMEP application along with "data.csv" (from TH2E),
     then open it in browser (http://linktoapp.com/TH2Eimport.php)

     Repeat as needed :-)

     Content of data.csv should look like this:
     tmp;     31.70;06/13/2015 19:24:00
     hum;     43.00;06/13/2015 19:24:00
   */

  // Connect to DB
  require "./config.php";
  require "./scripts/db.php";

  // Get data for import
  $data = file_get_contents("data.csv");

  // Process data
  $toImport = Array();
  $lines = explode("\n", $data);

  foreach($lines as $line)
  {

    $line = trim($line);
    $values = explode(";", $line);

    // Looks like we have something to process?
    if(count($values) == 3)
    {

      // Trim whitespaces
      $values[0] = trim($values[0]);
      $values[1] = trim($values[1]);
      $values[2] = trim($values[2]);

      // Check some simple conditions
      if(($values[0] == "tmp" OR $values[0] == "hum")
        AND is_numeric($values[1])
        AND strtotime($values[2]) !== false)
      {

        $date = date("Y-m-d H:i:s", strtotime($values[2]));
        $toImport[$date][$values[0]] = round($values[1], 1);

      }

    }

  }

  // Go through gathered data
  foreach($toImport as $date => $values)
  {

    // We need at least temperature
    if(is_numeric($values["tmp"]))
    {

      $qExists = mysqli_query($GLOBALS["DBC"], "SELECT id
                                                FROM tme
                                                WHERE kdy >= CAST('".substr($date, 0, 17)."00' AS datetime)
                                                  AND kdy <= CAST('".substr($date, 0, 17)."59' AS datetime)");

      if(mysqli_num_rows($qExists) > 0)
      {
        echo "<span style='color: darkgreen;'>{$date} - already have</span><br>";
      }
      else
      {

        echo "<span style='color: darkred;'>{$date} - missed, adding</span><br>";

        // Add
        mysqli_query($GLOBALS["DBC"], "INSERT INTO tme(kdy, teplota, vlhkost)
                                       VALUES('{$date}', '{$values["tmp"]}', '{$values["hum"]}');");

        echo mysqli_error($GLOBALS["DBC"]);

      }

    }

  }